package dao

import (
	"context"
	"goadmin/model"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func GetMsgListByUserId(userId uint) ([]model.Msg, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	cursor, err := mdb.Collection("msg").Find(ctx, bson.M{
		"$or": bson.A{
			bson.M{"toId": userId},
			bson.M{"fromId": userId},
		},
	})
	if err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)
	var msgs []model.Msg
	if err := cursor.All(ctx, &msgs); err != nil {
		return nil, err
	}
	return msgs, nil
}

func GetMsgListByConversation(userId1, userId2 uint, deadline time.Time, count int64) ([]model.Msg, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	cursor, err := mdb.Collection("msg").Find(ctx, bson.M{
		"$or": bson.A{
			bson.M{"toId": userId1, "fromId": userId2},
			bson.M{"toId": userId2, "fromId": userId1},
		},
		"createdAt": bson.M{"$lt": deadline},
	},
		options.Find().SetSort(bson.D{
			{Key: "createdAt", Value: -1},
		}).SetLimit(count),
	)
	if err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)
	var msgs []model.Msg
	if err := cursor.All(ctx, &msgs); err != nil {
		return nil, err
	}
	return msgs, nil
}

func InsertMsg(msg model.Msg) error {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	_, err := mdb.Collection("msg").InsertOne(ctx, msg)
	return err
}
